import _ from 'lodash';
import Im from 'immutable';
import {callStores} from 'core/decorators';


class Store {
    static stores = {};
    //static events = {};
    constructor(args) {
        // console.log(args);
        if (global.window && Store.stores[args.name]) {
            throw new Error('component instance\'s name have been named, you should give another name to this instance');
        }

        Store.stores[args.name] = this;
        this.stores = Store.stores;

        this.name = args.name;
        this.events = {};
        this.init(args);
        global.window.stores = Store.stores;
    }

    init(args) {
        for (let key in global.__iso_data[args.name]) {
            this[key] = global.__iso_data[args.name][key];
        }
        delete global.__iso_data[args.name];
    }

    on(event, fn) {
        // if (!Store.events[event]) Store.events[event] = [];
        // Store.events[event].push(fn);

        //由于on事件会无限push进去，所以我们限制每个地方只有一个on方法，多出的可以多fire一个事件出来区别
        // if (!this.events[event]) {
        this.events[event] = [];
        // }

        this.events[event].push(fn);

    }

    fire(event, data) {

        if (this.events[event]) this.events[event].forEach(fn => fn(data));
    }

    removeEvent(event, fn) {
        if (this.events[event]) {
            let fnIndex = this.events[event].indexOf(fn);
            if (!!~fnIndex) {
                this.events[event].splice(fnIndex, 1);
            }
        }
    }


    remove() {
        // console.log(Store.stores[this.name], Store.stores);
        // for (let event in this.events) {
        //     console.log(this.events);
        //     for (let i in this.events[event]) {
        //
        //         // let eventIndex = Store.events[event].indexOf(this.events[event][i]);
        //         // if (!!~eventIndex) {
        //         //     Store.events[event].splice(eventIndex, 1);
        //         // }
        //         console.log(i, this.events[event], event);
        //         this.events[event] = [];
        //         console.log(i, this.events[event], event);
        //     }
        // }
        this.events = {};
        delete Store.stores[this.name];
    }

}

// global.window.stores = Store.stores;

export default Store;

